<template>

  <div class="app-container ">

    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
      <!-- <el-form-item label="是否购买" prop="isBuy">
        <el-select v-model="queryParams.isBuy" placeholder="请输入是否购买" clearable @keyup.enter="handleQuery"
          style="width: 200px;">
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否启用" prop="isUse">
        <el-select v-model="queryParams.isUse" placeholder="请输入是否启用" clearable @keyup.enter="handleQuery"
          style="width: 200px;">
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="工具名称" prop="appName">
        <el-input v-model="queryParams.appName" placeholder="请输入工具名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <!-- <el-input v-model="queryParams.type" placeholder="请输入类型" clearable @keyup.enter="handleQuery" /> -->
        <el-tree-select v-model="queryParams.type" :data="toolCategoryList" placeholder="请选择类型"
          :props="{ value: 'id', label: 'categoryName', children: 'children' }" value-key="id" style="width: 220px;" />
      </el-form-item>
      <!-- <el-form-item label="平台名称" prop="toolType">
        <el-select v-model="queryParams.toolType" placeholder="请选择平台名称" clearable @change="handleGetToolKitOptions"
          style="width: 200px;">
          <el-option v-for="item in options.platformOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="工具包" prop="toolKitName">
        <el-select v-model="queryParams.toolKitName" placeholder="请选择工具包" clearable @change="handleQuery"
          style="width: 200px;">
          <el-option v-for="item in options.toolKitOptions" :key="item.toolKitName" :label="item.toolKitName"
            :value="item.toolKitName" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button icon="Upload" @click="handleUpload">上传</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <!-- <el-col :span="4" :xs="24" class="col-with-border-right">
        <div class="head-container">
          <el-tree :data="typeOptions" :props="{ label: 'toolType', children: 'children' }"
            :expand-on-click-node="false" ref="typeTreeRef" node-key="id" highlight-current default-expand-all
            @node-click="handleNodeClick" class="tree1" />
        </div>
      </el-col> -->

      <el-col :span="24" :xs="24">
      <el-card>
        <el-row :gutter="24">
    
          <el-col :span="4" v-for="(item, index) in dataList.filter(item => item.appName !== '基础工具包')" :key="index"
            style="margin-top: 15px;">
            <div class="d1" @click="handleIcon(item)" v-if="item.id == 0">
              <img :src="item.icon" class="circular-image">
              <span class="span1">{{ item.name }}</span>
            </div>

            <div class="d1" v-else 
              @contextmenu.prevent="showContextMenu($event, item)">
              <img :src="getSrc(item.appIconPath)" class="circular-image">
              <!-- <img :src="noCollection" class="top-right-img2" v-if="item.collectFlag != '1'"> -->
              <img :src="collection" class="top-right-img2" v-if="item.collectFlag == '1'">
              <img :src="buyIcon" class="top-right-img1" v-if="item.isBuy == '1'">
              <img :src="using" class="top-right-img" v-if="item.isUse == '1'">
              <span class="span1">{{ item.appName }}</span>
            </div>
          </el-col>
     
        </el-row>
             </el-card>
      </el-col>
    </el-row>



    <!-- 添加或修改App配置对话框 -->
    <el-dialog :title="addCardDialog.title" v-model="addCardDialog.open" width="800px" append-to-body>
      <el-form :model="addCardDialog.form" :rules="addCardDialog.rules" ref="appRef" label-width="160px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工具名称:" prop="appName">
              <el-input v-model="addCardDialog.form.appName" placeholder="请输入工具名称" />
              <!-- <el-select v-model="addCardDialog.form.appName" @change="hanldeAppNameToAppNameEn" placeholder="请选择工具名称" >
                <el-option v-for="item in options.appNameOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工具名称(英文&唯一):" prop="appNameEn">
              <el-input v-model="addCardDialog.form.appNameEn" placeholder="请输入工工具名称" />
              <!-- <el-select v-model="addCardDialog.form.appNameEn" disabled placeholder="请选择工具名称">
                <el-option v-for="item in options.appNameOptions" :key="item.id" :label="item.enName"
                  :value="item.id" />
              </el-select> -->
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="工具版本:" prop="appVersion">
              <el-input v-model="addCardDialog.form.appVersion" placeholder="请输入工具版本" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工具类型:" prop="type">
              <el-tree-select v-model="addCardDialog.form.type" :data="toolCategoryList"
                :props="{ value: 'id', label: 'categoryName', children: 'children' }" value-key="id" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-row>
          <el-col :span="12">
            <el-form-item label="平台名称:" prop="platformName">
              <el-select v-model="addCardDialog.form.platformName" placeholder="请选择平台名称"
                @change="handlePlatVerOptByPlatName">
                <el-option v-for="item in options.platformOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="平台版本:" prop="platformVersion">
              <el-select v-model="addCardDialog.form.platformVersion" placeholder="请输入平台版本">
                <el-option v-for="item in options.platformVersionOptions" :key="item.id" :label="item.name"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="方法名:" prop="methodName">
              <el-input v-model="addCardDialog.form.methodName" placeholder="请输入方法名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="节点类型:" prop="positionFlag">
              <el-input v-model="addCardDialog.form.positionFlag" placeholder="请输入节点类型" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述信息" prop="appDescribe">
              <el-input v-model="addCardDialog.form.appDescribe" type="textarea" :rows="2" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="工具图标:" prop="appIconPath">

              <el-upload :action="addCardDialog.url" :show-file-list="false" :on-success="handleIconSuccess"
                :headers="addCardDialog.headers" class="avatar-uploader" @mouseover="showMask = true"
                @mouseleave="addCardDialog.showMask = false" accept=".svg" :before-upload="beforeUploadAppIconPath">
                <div class="image-container">
                  <img v-if="addCardDialog.form.appIconPath" :src="getSrc(addCardDialog.form.appIconPath)"
                    class="avatar-img" />
                  <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                  </el-icon>
                  <div v-if="addCardDialog.showMask && addCardDialog.form.appIconPath" class="mask">
                    <el-button link type="primary" icon="Delete" @click.stop="deleteIcon()"
                      style="width: 30px ;height: 30px;"></el-button>
                  </div>
                </div>
              </el-upload>

            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-row>
          <el-col :span="24">
            <el-form-item label="工具文件:" prop="appFilePath">
              <el-upload v-model:file-list="addCardDialog.fileList" ref="uploadFilesRef" accept=".zip"
                :headers="addCardDialog.headers" :action="addCardDialog.url" :on-exceed="handleExceed"
                :on-success="handleFileSuccess" drag :limit="1" style="width: 300px; height: 250px">
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

                <template #tip>
                  <div class="el-upload__tip text-center">
                    <span>仅允许导入zip格式文件。</span>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row> -->


        <!-- <el-row style="margin-top: 20px;">
          <el-col :span="24">
            <el-form-item label="工具图片:" prop="appImgPath">
              <el-upload v-model:file-list="addCardDialog.imageList" ref="uploadImagesRef" :action="addCardDialog.url"
                list-type="picture-card" :on-remove="handleImageRemove" :on-success="handleImageSuccess"
                :on-preview="handlePictureCardPreview" :headers="addCardDialog.headers" accept=".png,.jpg,.jpeg">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>

              <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row> -->


      </el-form>
      <template #footer>
        <div class="dialog-footer" style="margin-right: 25px;">
          <el-button type="primary" @click="submitAppForm">确 定</el-button>
          <el-button @click="appCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog :title="appDetailsDialog.title" v-model="appDetailsDialog.open" width="900px" append-to-body>

      <div>
        <el-card class="card1">

          <el-row>
            <el-col :span="3">
              <img :src="getSrc(chooseApp.appIconPath)" class="circular-image1">
            </el-col>

            <el-col :span="18">
              <span class="span2">{{ chooseApp.appName }}</span>

              <div style=" display: flex; justify-content: flex-start; ">
                <div style="display: flex; align-items: center; margin-right: 10px;">
                  <img :src="duihao" style="width: 13px; height: 13px;" />
                  <span style="font-size: 12px;">安全认证</span>
                </div>

                <div style="display: flex; align-items: center; margin-right: 10px;">
                  <img :src="qian" style="width: 13px; height: 13px;" />
                  <span style="font-size: 12px;">收费</span>
                </div>
              </div>


              <div style="display: flex; align-items: center;">
                <el-tag type="warning" style="margin-right: 10px;">办公教育类下载榜第三名</el-tag>
                <el-tag type="info">PDF编辑</el-tag>
              </div>

            </el-col>

            <el-col :span="3" v-if="chooseApp.isBuy == '0'">
              <el-button type="primary" @click="menuItemClicked('buy')" round style="width: 80px;">购买</el-button>
            </el-col>
          </el-row>

          <el-row style="margin-top: 10px; justify-content: space-evenly;" class="container">
            <!-- <div class="d3">
              <span class="span3">评分</span>
              <img :src="xing" style="width: 10px; height: 10px; margin-right: 3px">
              <span>4.9</span>
            </div>
            <div class="d3">
              <span class="span3">下载量</span>
              <span>638万次</span>
            </div> -->
            <div class="d3">
              <span class="span3">安装所需空间</span>
              <span>{{ chooseApp.fileSize }}</span>
            </div>
            <div class="d3">
              <span class="span3">更新时间</span>
              <span>{{ chooseApp.updateTime }}</span>
            </div>
            <div class="d3">
              <span class="span3">版本号</span>
              <span>{{ chooseApp.appVersion }}</span>
            </div>
          </el-row>

        </el-card>

        <el-card class="card2">
          <img :src="dianzan">
          <span style="font-weight: bold;">超值活动：</span><span>具体有啥活动我也没想出来！</span>
        </el-card>

        <div style="margin-top: 20px;">
          <div style="display: flex; justify-content: space-evenly; margin-bottom: 20px;">
            <button class="btn1" @click="handleClickDiv(1)"
              :class="{ 'btnSelected': selectedObj.selectedButton === 1 }">
              详情
            </button>
            <!-- <button class="btn1" @click="handleClickDiv(2)"
              :class="{ 'btnSelected': selectedObj.selectedButton === 2 }">
              评论
            </button>
            <button class="btn1" @click="handleClickDiv(3)"
              :class="{ 'btnSelected': selectedObj.selectedButton === 3 }">
              问大家
            </button> -->
          </div>


          <div v-if="selectedObj.selectedButton === 1">
            <el-empty v-if="appDetailsDialog.imageList.length == 0" description="暂无详情图片" />
            <el-carousel v-else type="card">
              <el-carousel-item v-for="item in appDetailsDialog.imageList" :key="item">
                <el-image :src="item.url"
                  style=" height: 375px; background-position: center center; background-size: cover;"></el-image>
              </el-carousel-item>
            </el-carousel>
          </div>

          <div v-else-if="selectedObj.selectedButton === 2">
            <el-tag type="success" style="height: 60px; width: 100%; font-size: 22px;">看我干嘛，我没评论啊！</el-tag>
          </div>

          <div v-else-if="selectedObj.selectedButton === 3">
            <el-tag type="warning" style="height: 60px; width: 100%; font-size: 22px;">大家啥也没说！</el-tag>
          </div>

        </div>

        <div style="margin-top: 20px;">
          <span style="font-weight: bold; font-size: 22px; display: block">简介</span><br />
          <span style="margin-top: 20px ; font-size: 16px;">{{ chooseApp.appDescribe }}</span>
        </div>

      </div>


      <template #footer>
        <div class="dialog-footer" style="margin-right: 25px;">
          <el-button @click="appDetailsDialog.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <div v-if="rightTag.isMenuVisible" class="context-menu" @click.self="hideContextMenu" :style="rightTag.menuPosition"
      ref="excludeDiv">
      <ul>
        <!-- <li @click="menuItemClicked('open')">打开</li> -->
        <li @click="menuItemClicked('edit')">修改工具信息</li>
        <!-- <li @click="menuItemClicked('collect')" v-if="chooseApp.collectFlag != '1'">收藏</li>
        <li @click="menuItemClicked('noCollect')" v-if="chooseApp.collectFlag == '1'">取消收藏</li> -->
        <li @click="menuItemClicked('delete')" v-if="chooseApp.isUse != '1'">删除</li>
        <!-- <li @click="menuItemClicked('buy')" v-if="chooseApp.isBuy == '0'">购买</li>
        <li @click="menuItemClicked('using')" v-if="chooseApp.isUse == '0' && chooseApp.isBuy == '1'">启用</li>
        <li @click="menuItemClicked('noUsing')" v-if="chooseApp.isUse == '1' && chooseApp.isBuy == '1'">不启用</li> -->
      </ul>
    </div>


    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleDllFileSuccess"
        :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>

</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, toRefs, reactive } from 'vue';
import { ElButton, ElMessage, genFileId, ElMessageBox } from "element-plus";
import { listApp, getApp, delApp, addApp, updateApp, listAllApp } from "@/api/flow/appApi";
import fileIcon from '../../../assets/images/fileIcon.svg'
import dianzan from '../../../assets/images/dianzan.svg'
import duihao from '../../../assets/images/duihao.svg'
import qian from '../../../assets/images/qian.svg'
import using from '../../../assets/images/using.svg'
import buyIcon from '../../../assets/images/buyIcon.svg'
import { getToken } from "@/utils/auth";
import { getAppByType, listAppType } from '@/api/toolApp/appType';
import { Download } from '@element-plus/icons-vue';
import { listAllToolCategory } from "@/api/flow/toolCategory";

import collection from '../../../assets/images/collection.svg';
import noCollection from '../../../assets/images/noCollection.svg';
import func from '../../../../vue-temp/vue-editor-bridge';
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const dataList = ref<any>([]);
const tempNodeData = ref<any>({});
const toolCategoryList = ref([]);
const addCard = ref<any>([{
  id: 0,
  name: '添加工具',
  icon: fileIcon,
  version: '',
  describe: '',
}]);

interface AddCardDialog {
  open: boolean;
  title: string;
  showMask: boolean;
  form: Object;
  rules: {
    appName: Array<{ required: boolean; message: string; trigger: string }>;
  };
  fileList: Array<any>; // 根据实际文件类型定义更具体的类型
  imageList: Array<any>; // 根据实际图片类型定义更具体的类型
  headers: { Authorization: string };
  url: string;
}

const addCardDialog = ref<AddCardDialog>({
  open: false,
  title: '添加工具',
  showMask: false,
  form: {
    id: null,
    appName: null,
    appNameEn: null,
    appDescribe: null,
    appVersion: null,
    type: null,
    platformName: null,
    platformVersion: null,
    appIconPath: null,
    appImgPath: null,
    appFilePath: null,
    fileSize: null,
    showFlag: 0,
  },
  rules: {
    appName: [
      { required: true, message: '请输入工具名称', trigger: 'blur' },
    ],
  },
  fileList: [],
  imageList: [],
  headers: { Authorization: "Bearer " + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + "/common/upload",

});


const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,

    isBuy: null,
    isUse: null,

    appName: null,
    toolType: null,
    type: null,
    toolKitName: null,
  },

});

const { queryParams } = toRefs(data);


const chooseApp = ref<any>({})

const dialogImageUrl = ref<any>('')
const dialogVisible = ref<any>(false)

const options = ref<any>({
  appNameOptions: [],
  platformOptions: [],
  platformVersionOptions: [],
  toolKitOptions: [],
});

const appDetailsDialog = ref<any>({
  open: false,
  title: '工具详情',
  imageList: [],
});

const rightTag = ref<any>({
  isMenuVisible: false,
  menuPosition: { top: 0, left: 0 },
})

const typeOptions = ref<any>([]);

// const selectedButton  = ref<number>(1);
const selectedObj = ref<any>({
  selectedButton: 1,
  selectedButtonFlag: false,
});


const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/tool/app/importData"
});

const emit = defineEmits(['update'])
const props = defineProps({
  getParentList: {
    type: Function,
  },
});

onMounted(() => {
  getList();
  document.addEventListener('click', handleClickOutside);
  if (route.query.id && localStorage.getItem("reflushFlag")) {
    chooseApp.value = route.query;
    // menuItemClicked('edit')
    handleAppDetails(chooseApp.value);
    localStorage.removeItem("reflushFlag");
  }
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside);
})

let getList = () => {
  listAllApp(queryParams.value).then((res: any) => {
    dataList.value = addCard.value.concat(res.data);
  })
  getOptions();
  getListAllToolCategory();
}

let getOptions = () => {

}

/** 查询工具树结构列表 */
function getListAllToolCategory() {
  listAllToolCategory(queryParams.value).then(response => {
    // toolCategoryList.value = response.data;
    toolCategoryList.value = proxy.handleTree(response.data, "id");
  });
}

let handleGetToolKitOptions = (id: any) => {
  queryParams.value.toolKitName = null;
  options.value.toolKitOptions = [];

}
/** 搜索按钮操作 */
function handleQuery() {

  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

function handleUpload() {
  upload.title = "dll导入";
  upload.open = true;
}

/**文件上传中处理 */
const handleFileUploadProgress = (event: any, file: any, fileList: any) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleDllFileSuccess = (response: any, file: any, fileList: any) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};


let handleNodeClick = function (data: any, node: any, component: any): void {
  if (data.toolType == '总分类') return;

  tempNodeData.value = data;

  // getAppByType({ type: data.type }).then((res: any) => {
  //   dataList.value = addCard.value.concat(res.data);
  // })

  // listAllToolStructure({ toolType: data.toolType, ancestors: 1}).then((res: any) => {
  //   dataList.value = addCard.value.concat(res.data);
  // })

}

let getNameAndVersion = function (name: String, version: String) {
  if (version == '' || !version) {
    return name;
  } else {
    return name + ":" + version;
  }
}

let handleIcon = function (item: any) {

  reset();
  if (item.id == 0) {
    addCardDialog.value.open = true;
    addCardDialog.value.title = "添加工具";
  } else {
    getApp(item.id).then((res: any) => {
      if (res.data) {
        addCardDialog.value.form = res.data;
        if (res.data.platformName) {
          addCardDialog.value.form.platformName = parseInt(res.data.platformName);
        }
        if (res.data.platformVersion) {
          addCardDialog.value.form.platformVersion = parseInt(res.data.platformVersion);
        }
        if (addCardDialog.value.form.appFilePath) {
          addCardDialog.value.form.appFilePath.split(',').forEach((obj: any) => {
            if (obj) {
              addCardDialog.value.fileList.push({
                url: getSrc(obj),
                name: obj.split('/').pop(),
              });
            }
          })
        }

        if (addCardDialog.value.form.appImgPath) {
          addCardDialog.value.form.appImgPath.split(',').forEach((obj: any) => {
            if (obj) {
              addCardDialog.value.imageList.push({
                url: getSrc(obj),
                name: obj.split('/').pop(),
              });
            }
          })
        }

        if (res.data.type) {
          addCardDialog.value.form.type = Number(res.data.type)
        }

        addCardDialog.value.open = true;
        addCardDialog.value.title = "修改工具";
      }
    })
  }
}

let handleAppDetails = (item: any) => {
  appDetailsDialog.value.open = true;
  chooseApp.value = item;
  appDetailsDialog.value.imageList = [];
  if (chooseApp.value.appImgPath) {
    chooseApp.value.appImgPath.split(',').forEach((obj: any) => {
      if (obj) {
        appDetailsDialog.value.imageList.push({
          url: getSrc(obj),
          name: obj.split('/').pop(),
        });
      }
    })
  }
}

let reset = function () {
  addCardDialog.value.form = {
    id: null,
    appName: null,
    appNameEn: null,
    appDescribe: null,
    appVersion: null,
    type: null,
    platformName: null,
    platformVersion: null,
    appIconPath: null,
    appImgPath: null,
    appFilePath: null,
    fileSize: null,

    collectFlag: 0,
    showFlag: 0,
  };
  addCardDialog.value.fileList = [];
  addCardDialog.value.imageList = [];

  options.value.platformVersionOptions = [];
  proxy.resetForm("appRef");
}

let submitAppForm = function () {
  proxy.$refs.appRef.validate((valid: any) => {
    if (valid) {

      if (addCardDialog.value.imageList.length != 0) {
        addCardDialog.value.form.appImgPath = '';
        addCardDialog.value.imageList.forEach((element: any) => {

          if (element.response) {
            if (addCardDialog.value.form.appImgPath == '') {
              addCardDialog.value.form.appImgPath = element.response.url;
            } else {
              addCardDialog.value.form.appImgPath = addCardDialog.value.form.appImgPath + ',' + element.response.url;
            }
          } else {
            element.url = '/' + element.url.split('/').splice(2).join('/');
            if (addCardDialog.value.form.appImgPath == '') {
              addCardDialog.value.form.appImgPath = element.url;
            } else {
              addCardDialog.value.form.appImgPath = addCardDialog.value.form.appImgPath + ',' + element.url;
            }
          }

        });
      }
      // addCardDialog.value.form.type = tempNodeData.value.type;

      if (addCardDialog.value.form.id != null) {
        updateApp(addCardDialog.value.form).then((res: any) => {
          if (res.code == 200) {
            ElMessage.success(res.msg);
            // handleNodeClick(tempNodeData.value, null, null);
            getList();
            addCardDialog.value.open = false;
          } else {
            ElMessage.error(res.msg);
          }

          props.getParentList; // 调用父组件的方法
        })
      } else {
        addApp(addCardDialog.value.form).then((res: any) => {
          if (res.code == 200) {
            ElMessage.success(res.msg);
            // handleNodeClick(tempNodeData.value, null, null);
            getList();
            addCardDialog.value.open = false;
          } else {
            ElMessage.error(res.msg);
          }
          props.getParentList; // 调用父组件的方法
        })
      }
    }
  })
}

let appCancel = function (): void {
  addCardDialog.value.open = false;

}

let handleIconSuccess = function (response: any, file: any, fileList: any) {
  addCardDialog.value.form.appIconPath = response.url;
  // if(response.code == 500) {
  //   addCardDialog.value.form.appIconPath = '';
  //   ElMessage.error(response.msg);
  // }
}

let getSrc = function (url: String) {
  return import.meta.env.VITE_APP_BASE_API + url + '?version=' + Date.now();
}

let deleteIcon = function () {
  addCardDialog.value.form.appIconPath = '';
}

/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: any, fileList: any) => {
  if (response.code == 500) {
    ElMessage.error(response.msg);
  } else {
    addCardDialog.value.form.appFilePath = response.url;
    addCardDialog.value.form.fileSize = response.fileSize;
  }
};

const handleImageSuccess = (response: any, file: any, fileList: any) => {
  if (response.code == 500) {
    ElMessage.error(response.msg);
  }
  // else {
  //   addCardDialog.value.form.appImgPath = response.url;
  // }
};

const handlePictureCardPreview = (uploadFile: any) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
};

const handleImageRemove = (file: any, fileList: any) => {

}

const handleExceed = (files: any) => {
  proxy.$refs["uploadFilesRef"].clearFiles();
  var file = files[0];
  file.uid = genFileId();
  proxy.$refs["uploadFilesRef"].handleStart(file)
  proxy.$refs["uploadFilesRef"].submit();
}

const showContextMenu = (event: any, item: any) => {
  chooseApp.value = item;
  // 阻止默认的右键菜单
  event.preventDefault();

  // 更新菜单的位置
  rightTag.value.menuPosition = {
    top: event.clientY + 'px',
    left: event.clientX + 'px',
  }

  rightTag.value.isMenuVisible = true;

}

const hideContextMenu = () => {
  rightTag.value.isMenuVisible = false;
}

let menuItemClicked = (flag: any) => {
  //  @click="handleIcon(item)" @dblclick="handleAppDetails(item)"
  rightTag.value.isMenuVisible = false;
  if (flag == 'open') {
    handleAppDetails(chooseApp.value)
  } else if (flag == 'edit') {
    reset();
    handleIcon(chooseApp.value);
  } else if (flag == 'delete') {
    ElMessageBox.confirm('确认删除该工具吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      delApp(chooseApp.value.id).then((res: any) => {
        if (res.code == 200) {
          ElMessage.success(res.msg);
          // handleNodeClick(tempNodeData.value, null, null);
          getList();
          addCardDialog.value.open = false;
        }
      });
    })
  } else if (flag == 'buy') {
    // 调用接口记录购买数量
    //{
    //     "appId": 1,   //工具id
    //     "type": "0"   //0点击量 1购买量
    // }
    addUserBuyApp({ appId: chooseApp.value.id, appName: chooseApp.value.appName }).then((res: any) => {
      if (res.code == 200) {
        ElMessage.success(res.msg);
        chooseApp.value.isBuy = '1';
        getList();
      }
    })
  } else if (flag == 'using') {
    updateUserUseApp({ appId: chooseApp.value.id, isUse: '1' }).then((res: any) => {
      if (res.code == 200) {
        ElMessage.success(res.msg);
        getList();
      }
    })
  } else if (flag == 'noUsing') {
    updateUserUseApp({ appId: chooseApp.value.id, isUse: '0' }).then((res: any) => {
      if (res.code == 200) {
        ElMessage.success(res.msg);
        getList();
      }
    })
  } else if (flag == 'collect') {
    addUserAppCollect({ appId: chooseApp.value.id }).then((res: any) => {
      if (res.code == 200) {
        ElMessage.success(res.msg);
        getList();
      }
    })
  } else if (flag == 'noCollect') {
    removeUserAppCollect({ appId: chooseApp.value.id }).then((res: any) => {
      if (res.code == 200) {
        ElMessage.success(res.msg);
        getList();
      }
    })
  }

}

let handleClickOutside = (event: any) => {
  // 点击外部时隐藏菜单
  if (rightTag.value.isMenuVisible) {
    const excludeDiv = proxy.$refs.excludeDiv;
    if (!excludeDiv || !excludeDiv.contains(event.target)) {
      rightTag.value.isMenuVisible = false;
    }
  }
}

let downloadApp = () => {

  if (chooseApp.value.appFilePath) {
    // const url = window.location.origin + chooseApp.value.appFilePath;
    // const name = chooseApp.value.appName;
    // downloadFile(url, name);
    proxy.$download.zip(chooseApp.value.appFilePath, chooseApp.value.appName + '.zip')
  } else {
    ElMessage.error('文件路径为空')
  }
}

let downloadFile = (url: any, fileName: any) => {
  // 创建一个a标签
  const link = document.createElement("a");
  link.href = url; // 设置下载链接
  link.setAttribute("download", fileName); // 设置下载文件的名称
  // 阻止a标签的默认行为（比如打开新页面）
  link.target = "_blank";
  // 将a标签添加到文档中，但不在视口中显示
  document.body.appendChild(link);
  // 触发点击事件
  link.click();
  // 清理：从文档中移除a标签
  document.body.removeChild(link);
}

let handleClickDiv = (flag: Number) => {
  selectedObj.value.selectedButton = flag;
}

let handlePlatVerOptByPlatName = (id: any) => {
  addCardDialog.value.form.platformVersion = null;
  listAllToolStructure({
    parentId: id, ancestors: 2,
  }).then((res: any) => {
    options.value.platformVersionOptions = res.data;
  })
}

let beforeUploadAppIconPath = (file: any) => {

  const allowedTypes = ['svg'];
  const fileExtension = '.' + file.name.split('.').pop().toLowerCase();
  console.log(fileExtension);
  
  if (!allowedTypes.includes(fileExtension)) {
    ElMessage.error('文件格式不正确，仅支持 .svg 格式');
    return false;
  }
  return true;
}
</script>

<style scoped>
.circular-card {
  width: 200px;
  /* 卡片的宽度 */
  height: 200px;
  /* 卡片的高度，与宽度相同以形成圆形 */
  border-radius: 50%;
  /* 边框半径设置为50%以形成圆形 */
  background-color: #ffffff;
  /* 背景颜色 */
  display: flex;
  /* 使用Flexbox布局 */
  align-items: center;
  /* 子元素在交叉轴上居中对齐 */
  justify-content: center;
  /* 子元素在主轴上居中对齐 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  /* 添加阴影效果 */
  overflow: hidden;
  /* 隐藏溢出内容 */
}

.circular-image {
  max-width: 75px;
  /* 图片最大宽度为容器宽度 */
  max-height: 75px;
  /* 图片最大高度为容器高度 */
  border-radius: 15px;
  /* 图片也设置为圆形，但通常由于容器已经是圆形，这一步是多余的 */
  object-fit: cover;
  /* 图片保持比例并填充容器 */
  justify-content: center;
  margin: 0 auto;
  display: block;
}

.circular-image1 {
  max-width: 75px;
  /* 图片最大宽度为容器宽度 */
  max-height: 75px;
  /* 图片最大高度为容器高度 */
  border-radius: 15px;
  /* 图片也设置为圆形，但通常由于容器已经是圆形，这一步是多余的 */
  object-fit: cover;
  /* 图片保持比例并填充容器 */

  margin: left;
}

.col-with-border-right {
  position: relative;
}

.col-with-border-right::after {
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  width: 1.5px;
  /* 或者您想要的分割线宽度 */
  background-color: #a0a0a89d;
  /* Element UI 默认的分隔线颜色，您可以根据需要调整 */
}

.d1 {
  flex-direction: column;
  height: 170px;
  width: 170px;
  display: flex;
  justify-content: center;

  white-space: normal;
  word-wrap: break-word;
  overflow-wrap: break-word;
  position: relative;
  /* style="flex-direction: column;" */
}

.d1:hover {
  background-color: rgba(213, 215, 215, 0.721);
  border-radius: 15px;
  cursor: pointer;
}

.tree1 {
  font-family: '幼圆';
  font-weight: bold;
  font-size: 14px;
}

.span1 {
  /* style="font-size: 16px; margin-top: 15px; display: flex; justify-content: center;" */
  font-size: 16px;
  margin-top: 15px;
  /* display: inline-block; */
  max-width: 95%;
  text-align: center;
  /* justify-content: center; */

}

.image-container {
  position: relative;
  width: 150px;
  height: 150px;
  /* 根据你的图片大小调整 */
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  border: 1px solid var(--el-border-color);
  border-radius: 10px;
}

.top-right-img {
  position: absolute;
  top: 10px;
  /* 距离容器顶部 0px */
  right: 10px;
  /* 距离容器右侧 0px */
  width: 18px;
  /* 图像宽度 */
  height: 18px;
  /* 图像高度 */
}

.top-right-img1 {
  position: absolute;
  top: 10px;
  /* 距离容器顶部 0px */
  right: 38px;
  /* 距离容器右侧 0px */
  width: 18px;
  /* 图像宽度 */
  height: 18px;
  /* 图像高度 */
}

.top-right-img2 {
  position: absolute;
  top: 10px;
  /* 距离容器顶部 0px */
  right: 58px;
  /* 距离容器右侧 0px */
  width: 18px;
  /* 图像宽度 */
  height: 18px;
  /* 图像高度 */
}


.avatar-img {
  max-width: 100%;
  max-height: 100%;
}

.mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: space-around;
  align-items: center;
  /* flex-direction: column; */
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s, opacity 0.3s linear;
}

.image-container:hover .mask {
  visibility: visible;
  opacity: 1;
}

.mask button {
  color: white;
  border: none;
  background-color: transparent;
  cursor: pointer;
}

::v-deep .el-icon--close-tip {
  display: none !important;
}

.context-menu {
  margin: 0;
  background: #fff;
  position: fixed;
  background-color: white;
  border: 1px solid #ccc;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);
  z-index: 1000;
  list-style-type: none;
  padding: 5px 0;
  border-radius: 8px;
  font-size: 14px;
  color: #333
}

.context-menu ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.context-menu li {
  padding: 7px 16px;
  cursor: pointer;
}

.context-menu li:hover {
  background-color: #eee;
}

.card1 {
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(205, 186, 186, 0.2);
}

.card2 {
  border-radius: 8px;
  box-shadow: none;
  margin-top: 15px;
  background-color: #f5f7f9;

  display: flex;
  align-items: center;
}

.card2 img,
.card2 span {
  display: inline-block;
  vertical-align: middle;
  /* 垂直对齐中间 */
}

.card2 img {
  margin-right: 10px;
  width: 18px;
  height: 18px;
  margin-right: 5px;
}

.card2 span {
  margin-right: 10px;
}

.span2 {
  font-size: 22px;
  font-weight: bold;
  display: block;
  margin-bottom: 5px;
}

.span3 {
  font-size: 14px;
  color: #b9b9b9;
  display: block;
  /* 将第一个span设为块级元素，使其独占一行 */
  margin-bottom: 10px;
}

.d3 {
  margin: 5px 15px;
  text-align: center;
}

.container div {
  flex: 0.5;
  /* 或者使用具体的宽度值，但要减去边框的宽度 */
  border-right: 1px solid #ccc;
  /* 分割线 */
}

.container div:last-child {
  border-right: none;
  /* 移除最后一个div的右侧边框 */
}

.btn1 {

  font-weight: bold;
  font-size: 22px;

  width: 6vw;
  height: 35px;

  border-style: none;
  background-color: #ffffff;
  border-radius: 5px;

  color: #999999;
}

.btn1:hover {
  background-color: #dfe3e78f;
  color: #232323;
}

.btnSelected {
  background-color: #dfe3e78f;
  color: #232323;
}
</style>